from django.core.management.base import BaseCommand
from todo_app.models import TaskTemplate, Todo
from django.utils import timezone
import datetime

class Command(BaseCommand):
    help = 'Generates tasks from active templates based on their frequency.'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting task generation...'))
        today = timezone.now().date()
        templates = TaskTemplate.objects.all()
        created_count = 0

        for template in templates:
            should_create = False
            # 如果任务从未被创建过，则立即创建一个
            if template.last_created_date is None:
                should_create = True
            else:
                # 检查是否到了下一个创建周期
                if template.repeat_frequency == 'DAILY':
                    if (today - template.last_created_date).days >= 1:
                        should_create = True
                elif template.repeat_frequency == 'WEEKLY':
                    if (today - template.last_created_date).days >= 7:
                        should_create = True
                elif template.repeat_frequency == 'MONTHLY':
                    # 简单的按30天计算，可以根据需要实现更精确的月度逻辑
                    if (today - template.last_created_date).days >= 30:
                        should_create = True

            if should_create:
                Todo.objects.create(
                    user=template.user,
                    title=template.title,
                    content=template.content,
                    priority=template.priority,
                    category=template.category,
                    # 截止日期可以根据需要设置，这里默认为空
                    due_date=None
                )
                template.last_created_date = today
                template.save()
                created_count += 1
                self.stdout.write(self.style.SUCCESS(f'Task "{template.title}" created for user "{template.user.username}".'))

        self.stdout.write(self.style.SUCCESS(f'Task generation complete. {created_count} tasks created.')) 